import React, { useEffect, useState } from "react";
import Course from "../../components/course";
import { CapsuleTabs, Tabs } from "antd-mobile";
import "./index.scss";
import { categoryGet } from "../../api/course";
import { CategoryType } from "../../type/course";

type Props = {};

export default function Explore({}: Props) {
  const [cateList, setCateList] = useState<CategoryType[]>([]);
  const [idxLv1, setIdxLv1] = useState<string>("0");
  const [catelv2, setCateLv2] = useState<string>("");
  const [idxLv2, setIdxLv2] = useState<string>("0");
  useEffect(() => {
    categoryGet().then((res) => {
      let { results } = res.data;
      let arr = results.filter((item: CategoryType) => item.fatherId == "0-0");
      arr.forEach((item: CategoryType) => {
        item.children = results.filter(
          (child: CategoryType) => child.fatherId == item.objectId
        );
      });
      setCateList(arr);
    });
  }, []);
  const handleCapsule = (key: string) => {
    console.log(key);
    setIdxLv1(key);
    setIdxLv2("0"); //让子菜单激活【全部】
    setCateLv2(""); //让子类目id条件置空
  };
  const handleTabs = (key: string) => {
    setIdxLv2(key);
    if (key == "0") {
      setCateLv2("");
    } else {
      let { objectId } = cateList[Number(idxLv1)].children[Number(key) - 1];
      setCateLv2(objectId);
    }
  };
  return (
    <div>
      <h1 className="title">探索</h1>
      <div className="my-stick">
        <CapsuleTabs defaultActiveKey="0" onChange={handleCapsule}>
          {cateList.map((item, index) => {
            return <CapsuleTabs.Tab title={item.cateName} key={index} />;
          })}
        </CapsuleTabs>
        {cateList.length ? (
          <Tabs
            activeKey={idxLv2}
            stretch={false}
            className="cate-tabs"
            onChange={handleTabs}
          >
            <Tabs.Tab title="全部" key="0" />;
            {cateList[Number(idxLv1)].children.map((item, index) => {
              return <Tabs.Tab title={item.cateName} key={index + 1} />;
            })}
          </Tabs>
        ) : (
          ""
        )}
      </div>
      {cateList.length ? (
        <Course catelv1={cateList[Number(idxLv1)].objectId} catelv2={catelv2} />
      ) : (
        ""
      )}
    </div>
  );
}
